package com.lanyuan.a.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.lanyuan.a.atest.UserFormMap;
import com.lanyuan.a.bean.User;
import com.lanyuan.a.dao.BaseDao;
import com.lanyuan.a.service.UserService;
import com.lanyuan.plugin.PageView;

@Service("userService")
public class UserServiceImpl implements UserService{

	@Resource
	private BaseDao<User> baseDao;
	
	@Override
	public void saveUser(User user) {
		// TODO Auto-generated method stub
		baseDao.save(user);
	}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub
		baseDao.update(user);
	}

	@Override
	public User findUserById(int id) {
		return baseDao.get(User.class, id);
	}

	@Override
	public void deleteUser(User user) {
		baseDao.delete(user);
	}

	@Override
	public List<User> findAllList() {
		return baseDao.find("from User");
	}

	@Override
	public User findUserByNameAndPassword(User user) {
		return baseDao.get("from User u where u.accountname=? and u.password=?", new Object[]{user.getAccountname(),user.getPassword()});
	}

	@Override
	public long findUserByName(String username) {
		return baseDao.getCountByCondition("from User u where u.accountname=?", new Object[]{username});
	}

	@Override
	public List<User> queryByPage(UserFormMap formMap) {
		Long count = null;
		String ss = (String)formMap.get("accountname");
		PageView pageView = (PageView)formMap.get("paging");
		int first = pageView.getPageNow();
		int max = pageView.getPageSize();
		if(ss != null && !ss.equals("")){
			String hql = "from User u where accountname like :accountname";
			String countHql = "select count (1) from User u where accountname like ?";
			count = baseDao.getCountByConditionLike(countHql , new Object[]{ss});
			pageView.setRowCount(count);
			return baseDao.find(hql, new Object[]{"%"+ss+"%"}, first, max);
		}else{
			String countHql = "select count (1) from User u ";
			count = baseDao.count(countHql);
			pageView.setRowCount(count);
			return baseDao.find("from User u ", new Object[]{}, first , max);
		}
	}

	@Override
	public List<User> find(Integer page,Integer rows) {
		return baseDao.find("from User u ", new Object[]{}, page, rows);
	}

	@Override
	public void deleteUserById(String id) {
		// TODO Auto-generated method stub
		baseDao.delete("from User where id in (:ids)", "ids" , new Object[]{});
	}

	@Override
	public void deleteUserByIds(String[] ids) {
		Integer[] id = new Integer[ids.length];
		for(int i=0 ; i<ids.length; i++){
			System.out.println(ids[i]);
			id[i] = Integer.parseInt(ids[i]);
		}
		baseDao.delete("delete from User u where u.id in (:ids)","ids" , id);
	}

	@Override
	public List<User> findByRoot(int root) {
		return baseDao.find("from User u where u.root = ?", new Object[]{root});
	}

}
